<template>
  <div class="container">
    <div class="upload-img" :class="{ 'upload-img-error': upload.error }">
      <div v-if="limit > 1" class="image-list">
        <div
          v-for="(item, index) in upload.list"
          :key="index"
          class="item el-upload"
        >
          <span
            class="el-icon-circle-close"
            @click="removeUploadItem(index)"
          />
          <img :src="item.url">
        </div>

        <el-upload
          v-if="upload.list&&upload.list.length != limit"
          class="mb10"
          :multiple="false"
          :show-file-list="false"
          :auto-upload="false"
          accept=".jpg,.png,.jpeg"
          action="#"
          list-type="picture-card"
          :on-change="showCropperDialog"
        >
          <el-tooltip
            effect="dark"
            :content="tipContent"
            placement="bottom-start"
          >
            <i :class="upload.loading ? 'el-icon-loading' : 'el-icon-plus'" />
          </el-tooltip>
        </el-upload>
      </div>

      <el-upload
        v-else
        :multiple="false"
        :show-file-list="false"
        :auto-upload="false"
        accept=".jpg,.png,.jpeg"
        action="#"
        list-type="picture-card"
        :on-change="showCropperDialog"
      >
        <el-tooltip
          effect="dark"
          :content="tipContent"
          placement="bottom-start"
        >
          <img v-if="upload.url" :src="upload.url">
          <i
            v-else
            :class="upload.loading ? 'el-icon-loading' : 'el-icon-plus'"
          />
        </el-tooltip>
      </el-upload>
    </div>

    <!---->
    <el-dialog
      title="图片裁剪"
      :visible.sync="dialogShow"
      width="1000px"
      append-to-body
      :before-close="closeCropperDialog"
    >
      <div v-loading="upload.loading" class="cropper-content clearfix">
        <div class="cropper fl">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :output-size="option.size"
            :output-type="option.outputType"
            :info="true"
            :info-true="true"
            :full="option.full"
            :can-move="option.canMove"
            :can-move-box="option.canMoveBox"
            :original="option.original"
            :auto-crop="option.autoCrop"
            :auto-crop-width="autoCropWidth"
            :auto-crop-height="autoCropHeight"
            :fixed-box="fixedBox"
            :fixed="option.fixed"
            :center-box="option.centerBox"
            :fixed-number="fixedNumber"
            :enlarge="enlarge"
            @realTime="realTime"
          />
        </div>
        <!-- <div class="show-preview" :style="{height: containerPreviewsHeight}">
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img">
          </div>
        </div> -->
      </div>

      <el-row class="mt15">
        <el-button
          type="primary"
          icon="el-icon-zoom-in"
          @click="changeScale(1)"
        />
        <el-button
          type="primary"
          icon="el-icon-zoom-out"
          @click="changeScale(-1)"
        />
        <el-button type="primary" @click="rotateLeft">逆时针旋转</el-button>
        <el-button type="primary" @click="rotateRight">顺时针旋转</el-button>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCropperDialog">取 消</el-button>
        <el-button type="primary" :loading="upload.loading" @click="uploadImg">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import { uploadFile } from '@/api/common'
export default {
  name: '',
  components: { VueCropper },
  props: {
    initImg: {
      // 图片初始化
      type: [String, Array],
      default: null
    },
    autoCropWidth: {
      // 默认生成截图框宽度
      type: Number,
      default: 300
    },
    tipContent: {
      // 提示
      type: String,
      default: ''
    },
    autoCropHeight: {
      // 默认生成截图框高度
      type: Number,
      default: 300
    },
    fixedNumber: {
      // 截图框比例  (默认:[1:1])
      type: Array,
      default: function() {
        return [1, 1]
      }
    },
    limit: {
      // 上传数量类型 大于1 为多图上传
      type: Number,
      default: 1
    },
    enlarge: {
      // 截图框倍数
      type: Number,
      default: 1
    },
    fixedBox: {
      // 固定截图框大小 不允许改变  (默认:false)
      type: Boolean,
      default: false
    },
    returnObj: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      upload: {
        url: this.initImg ? this.initImg : '', // 上传后的地址
        loading: false,
        error: false,
        list: this.initImg ? this.initImg : []
      },
      dialogShow: false,
      previews: {}, // 预览数据
      option: {
        img: '', // 裁剪图片的地址  (默认：空)
        outputSize: 1, // 裁剪生成图片的质量  (默认:1)
        full: false, // 是否输出原图比例的截图 选true生成的图片会非常大  (默认:false)
        outputType: 'png', // 裁剪生成图片的格式  (默认:jpg)
        canMove: true, // 上传图片是否可以移动  (默认:true)
        original: false, // 上传图片按照原始比例渲染  (默认:false)
        canMoveBox: true, // 截图框能否拖动  (默认:true)
        autoCrop: true, // 是否默认生成截图框  (默认:false)
        autoCropWidth: 300, // 默认生成截图框宽度  (默认:80%)
        autoCropHeight: 300, // 默认生成截图框高度  (默认:80%)
        fixedBox: true, // 固定截图框大小 不允许改变  (默认:false)
        fixed: true, // 是否开启截图框宽高固定比例  (默认:true)
        centerBox: true, // 截图框是否被限制在图片里面
        fixedNumber: [1.5, 1], // 截图框比例  (默认:[1:1])
        enlarge: 1
      },
      isDisabled: false,
      downImg: '#',
      fileName: ''
    }
  },
  computed: {
    containerPreviewsHeight() {
      const fixedNumber = this.fixedNumber
      const height = (300 / fixedNumber[0]) * fixedNumber[1] + 'px'
      return height
    }
  },
  watch: {
    initImg(e) {
      if (this.limit > 1) {
        if (e) {
          this.upload.list = e
        } else {
          this.upload.list = []
        }
      } else {
        this.upload.url = e
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 销毁
  destroyed() {},
  // 方法
  methods: {
    // 初始化
    initUpload(url) {
      if (this.limit > 1) {
        this.upload.list = url || []
        this.upload.url = ''
      } else {
        this.upload.list = []
        this.upload.url = url || ''
      }
      this.upload.error = false
    },
    // 重置
    resetUpload() {
      this.upload = {
        url: '', // 上传后的地址
        loading: false,
        error: false,
        list: []
      }
    },
    // 多图片时删除
    removeUploadItem(index) {
      this.upload.list.splice(index, 1)
      // 更新父组件ids
      this.returnFatherData()
    },
    // 错误显示
    uploadError(falg) {
      this.upload.error = falg
    },
    // 关闭裁剪框
    closeCropperDialog() {
      this.dialogShow = false
      this.upload.loading = false
      this.$refs.cropper.clearCrop() // 清除截图
    },
    // 打开裁剪框
    showCropperDialog(file) {
      console.log(file)
      if (this.limit > 1) {
        if (this.limit == this.upload.list.length) {
          this.$message.error('最多只能上传' + this.limit + '张图片')
          return
        }
      }
      const type = file.name.split('.').pop().toLowerCase()
      this.fileName = file.name
      const isJPG = type === 'jpeg' || type === 'png' || type === 'jpg'
      if (!isJPG) {
        this.$message.error('上传格式不正确!')
        this.upload.loading = false
      } else {
        this.option.img = file.url
        this.dialogShow = true
      }
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 实时预览
    realTime(data) {
      this.previews = data
    },
    // 将剪裁好的图片回传给父组件
    uploadImg() {
      const that = this
      this.upload.loading = true
      // let axis = this.$refs.cropper.getCropAxis();// 获取切图坐标
      // this.$refs.cropper.getCropData(data => { base64模式
      //     setTimeout(function(){
      //       that.upload = {
      //         url: window.URL.createObjectURL(that.dataURItoBlob(data)),
      //         loading: false,
      //         error: false
      //       }
      //       that.closeCropperDialog();
      //       // 调用上传接口
      //       // 上传成功后返回id 给父组件
      //       that.$emit('getUploadImg', "11111");
      //     },1500)
      //   });
      this.$refs.cropper.getCropBlob((data) => {
        const formData = new FormData()
        formData.append('file', data, this.fileName)
        const date = new Date()
        formData.append('biz', 'public/tailoring/' + date.getFullYear() + '/' + parseInt(date.getMonth() + 1) + '/' + date.getDate())
        // 模拟上传
        uploadFile(formData).then((response) => {
          if (that.limit > 1) {
            const list = that.upload.list
            list.push({
              url: window.URL.createObjectURL(data),
              id: response.result.fileId
            })
            that.upload = {
              list: list,
              loading: false,
              error: false
            }
            that.returnFatherData()
          } else {
            that.upload = {
              url: window.URL.createObjectURL(data),
              loading: false,
              error: false
            }
            that.returnFatherData(this.returnObj ? response.result : response.result.fileId)
          }
          that.closeCropperDialog()
        }).catch(err => {
          this.upload.loading = false
        })
      })
    },
    // base64转成bolb对象
    dataURItoBlob(base64Data) {
      let byteString
      if (base64Data.split(',')[0].indexOf('base64') >= 0) {
        byteString = atob(base64Data.split(',')[1])
      } else {
        byteString = unescape(base64Data.split(',')[1])
      }
      const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0]
      const ia = new Uint8Array(byteString.length)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }
      return new Blob([ia], { type: mimeString })
    },
    // 返回给父组件id， 多文件循环出封装为 ids字符串 （例子：id1,id2,id3）
    returnFatherData(id) {
      if (this.limit > 1) {
        const list = this.upload.list
        const arr = []
        for (let i = 0; i < list.length; i++) {
          arr.push(list[i].id)
        }
        this.$emit('upload', arr.join(','))
      } else {
        this.$emit('upload', id)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.cropper-content {
  .cropper {
    width: 100%;
    height: 400px;
  }
  .show-preview {
    width: 300px;
    float: right;
    overflow: hidden;
    border: 1px solid #cccccc;
    background: #cccccc;
    display: flex;
    align-items: center;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
  }
}
// 根据需求在每个页面设置不同大小
// .upload-img{
//   ::v-deep {
//     .el-upload{width: 84px; height: 84px;line-height: 84px;}
//   }
//
// }
.upload-img {
  ::v-deep {
    .el-upload {
      padding: 2px;
    }
  }
  img {
    width: 100%;
    height: 100%;
    border-radius: 5px;
  }
}
.upload-img-error {
  ::v-deep {
    .el-upload {
      border-color: #ff4949;
    }
  }
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  .item {
    margin-bottom: 10px;
    margin-right: 10px;
    position: relative;
    height: 100%;
    line-height: 0;
    span {
      position: absolute;
      right: -8px;
      top: -8px;
      font-size: 16px;
      color: #999;
      cursor: pointer;
    }
    img {
      width: 100%;
    }
  }
}
</style>
